﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WanMeiModel;

namespace WanMeiClient
{
    /// <summary>
    /// redis数据与数据库数据的获取中间件
    /// </summary>
    internal class DataIntegration
    {
        //封装先从缓存取数据，没有，从数据库取数据，再存到缓存的过程（有参数）
        internal static T GetData<T>(string key, Func<InputArgs, T> func,InputArgs item)
        {
            T result = RedisManager.Get<T>(key);
            if (result == null)
            {
                result = func(item);
                if (result != null)
                {
                    if (result is ICollection)
                    {
                        var temp = result as ICollection;
                        if (temp.Count > 0)
                        {
                            RedisManager.Set<T>(key, result, DateTime.Now.AddHours(24));
                        }
                    }
                    else
                    {
                        RedisManager.Set<T>(key, result, DateTime.Now.AddHours(24));
                    }
                    
                }
            }
            return result;
        }
        /// <summary>
        /// //封装先从缓存取数据，没有，从数据库取数据，再存到缓存的过程（无参数）
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="func"></param>
        /// <returns></returns>
        internal static T GetData<T>(string key, Func<T> func)
        {
            T result = RedisManager.Get<T>(key);
            if (result == null)
            {
                result = func();
                if (result != null)
                {
                    if (result is ICollection)
                    {
                        var temp = result as ICollection;
                        if (temp.Count > 0)
                        {
                            RedisManager.Set<T>(key, result, DateTime.Now.AddHours(24));
                        }
                    }
                    else
                    {
                        RedisManager.Set<T>(key, result, DateTime.Now.AddHours(24));
                    }

                }
            }
            return result;
        }
    }
}